package com.chookss.home.knowledge;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chookss.R;
import com.chookss.Urls;
import com.chookss.home.entity.NavigationEntity;
import com.chookss.home.gallery.PublishGalleryActivity;
import com.chookss.home.knowledge.adaper.KnowledgeMoreFunctionAdapter;
import com.chookss.home.publish.PublishVedioActivity;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.PathUtil;
import com.chookss.tools.PermissionUtils;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.GlideEngine;
import com.chookss.view.ImageFileCompressEngine;
import com.chookss.view.consecutivescroller.ConsecutiveScrollerLayout;
import com.google.gson.reflect.TypeToken;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.luck.picture.lib.animators.AnimationType;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.lvgroup.hospital.base.BaseAct;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class KnowledgeMoreFunctionActivity extends BaseAct {


    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.rvViewApply)
    RecyclerView rvViewApply;
    @BindView(R.id.rvViewTools)
    RecyclerView rvViewTools;
    @BindView(R.id.rvViewAudit)
    RecyclerView rvViewAudit;
    @BindView(R.id.srlView)
    ConsecutiveScrollerLayout srlView;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    private KnowledgeMoreFunctionAdapter applyAdapter, toolsAdapter,auditAdapter;
    private ArrayList<NavigationEntity> navigationApplyList = new ArrayList<>();
    private ArrayList<NavigationEntity> navigationToolsList = new ArrayList<>();
    private ArrayList<NavigationEntity> navigationAuditList = new ArrayList<>();
    private ArrayList<NavigationEntity> selectDataList = new ArrayList<>();
    private int type = 0;//0默认状态 1显示是否选中状态

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_knowledge_more_function);
        ButterKnife.bind(this);
        initState();
    }

    @Override
    public void initData() {
        commonTitleTxt.setText("精选");
        type = getIntent().getIntExtra("type", 0);
        selectDataList = (ArrayList<NavigationEntity>) getIntent().getSerializableExtra("selectData");
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 5);
        rvViewApply.setLayoutManager(gridLayoutManager);
        applyAdapter = new KnowledgeMoreFunctionAdapter(R.layout.item_home_knowledge_more_function, this, navigationApplyList, type);
        rvViewApply.setAdapter(applyAdapter);

        GridLayoutManager gridLayoutManage2 = new GridLayoutManager(this, 5);
        rvViewAudit.setLayoutManager(gridLayoutManage2);
        auditAdapter = new KnowledgeMoreFunctionAdapter(R.layout.item_home_knowledge_more_function, this, navigationAuditList, type);
        rvViewAudit.setAdapter(auditAdapter);

        GridLayoutManager gridLayoutManage3 = new GridLayoutManager(this, 5);
        rvViewTools.setLayoutManager(gridLayoutManage3);
        toolsAdapter = new KnowledgeMoreFunctionAdapter(R.layout.item_home_knowledge_more_function, this, navigationToolsList, type);
        rvViewTools.setAdapter(toolsAdapter);
        showLoading();
        getNavigations();
    }

    public void getNavigations() {
        //获取导航
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<NavigationEntity>>>() {
        }.getType(), null, Urls.selectByRole, SignUtils2.makeSignStr(null), false, new ObserverCallback<List<NavigationEntity>>() {
            @Override
            public void onSuccess(List<NavigationEntity> data) {
                dismissLoading();
                if (data.size() > 0) {
                    List<NavigationEntity> list = new ArrayList<>();
                    list.addAll(data);
                    navigationToolsList.clear();
                    navigationApplyList.clear();
                    navigationAuditList.clear();
                    // 01公告 02 日志 03资料 04学习计划05考试 06 面试 07 通讯录 08  个人能力09 我的待办10 发布视频11 发布新闻12发布日志13题库14视频15溯源
                   //    16图文发布17图文18邀请注册19 小视频  20 面试评价21日报22周报23月报24知识库25发布图库26图库27考勤28请假29电子工牌30报销31物料32借款33补贴34计步器
                    //35刻章  36巡检  37工资条  38离职  39晋升  40项目管理 41加班
                    for (int i = 0; i < list.size(); i++) {
                        NavigationEntity navigationEntity = list.get(i);
                        if ("10".equals(navigationEntity.getNavigationCode()) || "11".equals(navigationEntity.getNavigationCode()) || "12".equals(navigationEntity.getNavigationCode()) || "16".equals(navigationEntity.getNavigationCode()) || "21".equals(navigationEntity.getNavigationCode()) || "22".equals(navigationEntity.getNavigationCode()) || "23".equals(navigationEntity.getNavigationCode()) || "18".equals(navigationEntity.getNavigationCode()) || "09".equals(navigationEntity.getNavigationCode()) || "20".equals(navigationEntity.getNavigationCode())|| "25".equals(navigationEntity.getNavigationCode())) {
                            navigationToolsList.add(navigationEntity);
                        }else if ("27".equals(navigationEntity.getNavigationCode()) || "28".equals(navigationEntity.getNavigationCode()) || "30".equals(navigationEntity.getNavigationCode()) || "31".equals(navigationEntity.getNavigationCode()) || "32".equals(navigationEntity.getNavigationCode()) || "33".equals(navigationEntity.getNavigationCode()) || "35".equals(navigationEntity.getNavigationCode()) || "38".equals(navigationEntity.getNavigationCode()) || "39".equals(navigationEntity.getNavigationCode()) || "40".equals(navigationEntity.getNavigationCode())|| "41".equals(navigationEntity.getNavigationCode())) {
                            navigationAuditList.add(navigationEntity);
                        } else {
                            navigationApplyList.add(navigationEntity);
                        }
                    }
                    if (type == 1) {
                        setData();
                    }else{
                        applyAdapter.notifyDataSetChanged();
                        toolsAdapter.notifyDataSetChanged();
                        auditAdapter.notifyDataSetChanged();
                    }

                } else {
                    llNone.setVisibility(View.VISIBLE);
                    srlView.setVisibility(View.GONE);
                }
            }

            @Override
            public void onError(String errorMsg) {
                dismissLoading();
                MyToast.show(errorMsg);
            }
        });
    }

    private void setData() {
        for (int i = 0; i < navigationApplyList.size(); i++) {
            for (int j = 0; j < selectDataList.size(); j++) {
                if (selectDataList.get(j).getNavigationCode().equals(navigationApplyList.get(i).getNavigationCode())) {
                    navigationApplyList.get(i).setSelect(true);
                }
            }
        }

        for (int i = 0; i < navigationAuditList.size(); i++) {
            for (int j = 0; j < selectDataList.size(); j++) {
                if (selectDataList.get(j).getNavigationCode().equals(navigationAuditList.get(i).getNavigationCode())) {
                    navigationAuditList.get(i).setSelect(true);
                }
            }
        }

        for (int i = 0; i < navigationToolsList.size(); i++) {
            for (int j = 0; j < selectDataList.size(); j++) {
                if (selectDataList.get(j).getNavigationCode().equals(navigationToolsList.get(i).getNavigationCode())) {
                    navigationToolsList.get(i).setSelect(true);
                }
            }
        }
        applyAdapter.notifyDataSetChanged();
        toolsAdapter.notifyDataSetChanged();
        auditAdapter.notifyDataSetChanged();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();
        } else {
            String msg = messageEvent.getMessage();
            if (!Utils.isNull(msg)) {
                if (msg.equals("KnowledgeMoreReleasedVideo")) {
                    requestSTORAGECamer(0);
                }else  if (msg.equals("KnowledgeMoreReleasedGallery")) {
                    requestSTORAGECamer(1);
                }
            }
        }
    }

    private void requestSTORAGECamer(int type) {
        XXPermissions.with(this)
                .permission(Permission.CAMERA)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> granted, boolean all) {
                        if (all) {
                            if (type == 0) {
                                //发布视频
                                PictureSelector.create(KnowledgeMoreFunctionActivity.this)
                                        .openGallery(SelectMimeType.ofVideo())
                                        .isDisplayCamera(true)//是否显示相机入口
                                        .setMaxVideoSelectNum(1)
                                        .setMaxSelectNum(1)
                                        .setSelectionMode(SelectModeConfig.SINGLE)//单选
                                        .isPreviewVideo(true)//是否支持预览视频
                                        .setSelectMinFileSize(50)//过滤最小文件50k
                                        .setFilterVideoMaxSecond(600)//过滤最大视频选择600s
                                        .setRecordVideoMaxSecond(30)//过滤录制最大30s
                                        .isFilterSizeDuration(true)//是否过滤图片或音视频大小时长为0的资源
                                        .setRecyclerAnimationMode(AnimationType.SLIDE_IN_BOTTOM_ANIMATION)
                                        .setImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                                        .forResult(PictureConfig.REQUEST_CAMERA);
                            }else{
                                //发布图片
                                PictureSelector.create(KnowledgeMoreFunctionActivity.this)
                                        .openGallery(SelectMimeType.ofImage())
                                        .isDisplayCamera(true)//是否显示相机入口
                                        .setMaxSelectNum(9)
                                        .setSelectionMode(SelectModeConfig.MULTIPLE)//多选
                                        .isPreviewImage(true)//是否支持预览图片
                                        .setCompressEngine(ImageFileCompressEngine.createGlideEngine())
                                        .setRecyclerAnimationMode(AnimationType.SLIDE_IN_BOTTOM_ANIMATION)
                                        .setImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                                        .forResult(PictureConfig.CHOOSE_REQUEST);
                            }

                        } else {
                            PermissionUtils.errorPermission(KnowledgeMoreFunctionActivity.this, granted, all);
                        }
                    }

                    @Override
                    public void onDenied(List<String> denied, boolean quick) {
                        PermissionUtils.errorPermission(KnowledgeMoreFunctionActivity.this, denied, quick);
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @androidx.annotation.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == PictureConfig.REQUEST_CAMERA) {
                List<LocalMedia> selectList = PictureSelector.obtainSelectorList(data);
                Intent intent = new Intent(KnowledgeMoreFunctionActivity.this, PublishVedioActivity.class);
                String url = "";
                if (selectList.get(0).getPath().contains("content://")) {
                    Uri uri = Uri.parse(selectList.get(0).getPath());
                    url = PathUtil.getPath(this, uri);
                } else {
                    url = selectList.get(0).getPath();
                }
                intent.putExtra("fileUrl", url);
                KLog.i("原图::" + selectList.get(0).getPath());
                KLog.i("Android Q 特有Path::" + Uri.parse(selectList.get(0).getPath()).toString());
                startActivity(intent);
            } else if(requestCode==PictureConfig.CHOOSE_REQUEST){
                // 如果是直接从相册获取
                List<LocalMedia> selectList = PictureSelector.obtainSelectorList(data);
                ArrayList<String> imgList=new ArrayList<>();
                for (int i = 0; i < selectList.size(); i++) {
                    KLog.i("压缩::" + selectList.get(0).getCompressPath());
                    KLog.i("原图::" + selectList.get(0).getPath());
                    String url = "";
                    if (!Utils.isNull(selectList.get(i).getCompressPath())) {
                        if (selectList.get(i).getCompressPath().contains("content://")) {
                            Uri uri = Uri.parse(selectList.get(i).getCompressPath());
                            url = PathUtil.getPath(this, uri);
                        } else {
                            url = selectList.get(i).getCompressPath();
                        }
                    } else {
                        if (selectList.get(i).getPath().contains("content://")) {
                            Uri uri = Uri.parse(selectList.get(i).getPath());
                            url = PathUtil.getPath(this, uri);
                        } else {
                            url = selectList.get(i).getPath();
                        }
                    }
                    imgList.add(url);
                    KLog.i("Android Q 特有Path::" + url);
                }
                if(imgList.size()>0){
                    Intent intent = new Intent(KnowledgeMoreFunctionActivity.this, PublishGalleryActivity.class);
                    intent.putStringArrayListExtra("imgUrls",imgList);
                    startActivity(intent);
                }
            }
        }
    }

    @OnClick(R.id.common_title_back)
    public void onClick() {
        toFinish();
    }

    private void toFinish() {
        if (type == 1) {
            EventBus.getDefault().post(new MyEvent("updateHomeKnowledgeDialog"));
        }
        finish();
    }

    @Override
    public void onBackPressed() {
        toFinish();
    }
}
